use gloo_utils::format::JsValueSerdeExt;
use log::info;
use serde::{Deserialize, Serialize};
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
use web_sys::{window, Response};
use yew::prelude::*;

use super::components::detail::{Detail, DetailResponse};

#[derive(Serialize, Deserialize, Properties, PartialEq)]
pub struct DetailProps {
    pub id: String,
}

#[function_component]
pub fn App(props: &DetailProps) -> Html {
    let id = &props.id;

    let detail_id = use_state(move || id.clone());
    let data = use_state(|| Detail::new());

    let data_set = data.clone();
    let get_data = Closure::wrap(Box::new(move |value: JsValue| {
        let data = value.into_serde::<DetailResponse>().unwrap();

        if data.success {
            data_set.set(data.data);
        };
    }) as Box<dyn FnMut(JsValue)>);
    let cb = Closure::wrap(Box::new(move |value: JsValue| {
        let res = value.dyn_into::<Response>().unwrap();
        let json = res.json().unwrap();

        let _ = json.then(&get_data);
    }) as Box<dyn FnMut(JsValue)>);

    let query_id = detail_id.clone();
    use_effect_with(query_id, move |query_id| {
        let url = format!("https://cnodejs.org/api/v1/topic/{}", *(query_id.clone()));
        info!("{}", url);

        let window = window().unwrap();
        let _ = window.fetch_with_str(&url).then(&cb);

        || cb.forget()
    });
    html! {
        <div class="cnode detail">
            <h3 class="title">{format!("{}",data.title)}</h3>
            <div class="content">{format!("{}",data.content)}</div>
        </div>
    }
}
